<?php
/**
 * @ClassName: PaymentLogic
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-10-22 18:29
 * @Version: V1.0.0
 */

namespace app\common\huifu;

use think\facade\Log;

class PaymentLogic
{
    public function __construct()
    {
        Sdk::init(); //初始化sdk
        Log::init(['type' => 'File', 'path' => app()->getRuntimePath() . 'log' . DIRECTORY_SEPARATOR . 'huifu/payment']);
    }

    function getHuifuId($trade_no = '')
    {
        //目前是单商户下多用户体系，商户号为默认的主账号
        return ['code' => 1, 'msg' => 'ok', 'data' => \BsPaySdk\core\BsPay::getConfig()->sys_id];
    }

    /**
     * 微信 APP 支付
     * @param $trade_no
     * @param $description
     * @param $total_amount
     * @return array
     */
    function wxpayOfApp($trade_no, $description, $total_amount)
    {
        /**
         * app走微信小程序，拉起小程序支付
         */
        return [
            'code' => 1,
            'msg' => '拉起小程序',
            'micro_pro_accid' => config('huifu.accid_mp'), //要跳转的小程序原始id，gh_xxxxxxx
            'mp_type' => 2, //小程序版本状态 0-正式版； 1-测试版； 2-体验版。 默认值为0。
        ];
    }

    /**
     * 微信小程序
     * @param $trade_no
     * @param $description
     * @param $total_amount
     * @param $openid
     * @return mixed
     */
    function wxpayOfMicroPro($trade_no, $description, $total_amount, $openid)
    {
        $total_amount = number_format($total_amount, 2, '.', ''); //两位小数格式
        $request = new \BsPaySdk\request\V2TradePaymentJspayRequest();
        // 请求日期
        $request->setReqDate(date("Ymd"));
        // 请求流水号
        $request->setReqSeqId($trade_no . '_hf' . time());
        // 商户号
        $huifu_res = $this->getHuifuId($trade_no);
        if ($huifu_res['code'] == 0) {
            return $huifu_res;
        }
        $request->setHuifuId($huifu_res['data']);
        // 商品描述
        $request->setGoodsDesc($description);
        // 交易类型
        $request->setTradeType("T_MINIAPP");
        // 交易金额
        $request->setTransAmt($total_amount);

        $extendInfoMap = [
            "req_seq_id" => $trade_no . '_hf' . time(), // 唯一请求流水号，覆盖，不使用它自动生成的
            'notify_url' => 'http://' . request()->host() . '/api/huifupay/wechatnotify',
            'acct_split_bunch' => $this->acctSplitBunch($trade_no, $total_amount), //分账信息
            'wx_data' => json_encode([
                'sub_appid' => config('huifu.appid_mp'), //小程序appid
                'sub_openid' => $openid,
            ]),
        ];
        $request->setExtendInfo($extendInfoMap);

        // 发起API调用
        $client = new \BsPaySdk\core\BsPayClient();
        $result = $client->postRequest($request);
        return $this->getResult($result, $trade_no);
    }

    /**
     * 支付宝 APP 支付
     * @param $trade_no
     * @param $description
     * @param $total_amount
     * @return mixed
     */
    function alipayOfApp($trade_no, $description, $total_amount)
    {
        $total_amount = number_format($total_amount, 2, '.', ''); //两位小数格式

        $request = new \BsPaySdk\request\V2TradePaymentJspayRequest();
        // 请求日期
        $request->setReqDate(date("Ymd"));
        // 请求流水号
        $request->setReqSeqId($trade_no . '_hf' . time());
        // 商户号
        $huifu_res = $this->getHuifuId($trade_no);
        if ($huifu_res['code'] == 0) {
            return $huifu_res;
        }
        $request->setHuifuId($huifu_res['data']);
        // 商品描述
        $request->setGoodsDesc($description);
        // 交易类型
        $request->setTradeType("A_NATIVE");
        // 交易金额
        $request->setTransAmt($total_amount);

        $extendInfoMap = [
            "req_seq_id" => $trade_no . '_hf' . time(), // 唯一请求流水号，覆盖，不使用它自动生成的
            'notify_url' => 'http://' . request()->host() . '/api/huifupay/alipaynotify',
            'acct_split_bunch' => $this->acctSplitBunch($trade_no, $total_amount), //分账信息
        ];
        $request->setExtendInfo($extendInfoMap);

        // 发起API调用
        $client = new \BsPaySdk\core\BsPayClient();
        $result = $client->postRequest($request);

        // var_dump($result);

        return $this->getResult($result, $trade_no);
    }

    /**
     * 微信公众号支付
     * @param $trade_no
     * @param $description
     * @param $total_amount
     * @param $openid
     * @return mixed
     */
    function wxpayOfH5($trade_no, $description, $total_amount, $openid)
    {
        $total_amount = number_format($total_amount, 2, '.', ''); //两位小数格式

        $request = new \BsPaySdk\request\V2TradePaymentJspayRequest();
        // 请求日期
        $request->setReqDate(date("Ymd"));
        // 请求流水号
        $request->setReqSeqId($trade_no . '_hf' . time());
        // 商户号
        $huifu_res = $this->getHuifuId($trade_no);
        if ($huifu_res['code'] == 0) {
            return $huifu_res;
        }
        $request->setHuifuId($huifu_res['data']);
        // 商品描述
        $request->setGoodsDesc($description);
        // 交易类型
        $request->setTradeType("T_JSAPI");
        // 交易金额
        $request->setTransAmt($total_amount);

        $extendInfoMap = [
            'notify_url' => 'http://' . request()->host() . '/api/huifupay/wechatnotify',
            'acct_split_bunch' => $this->acctSplitBunch($trade_no, $total_amount), //分账信息
            'wx_data' => json_encode([
                'sub_appid' => config('huifu.appid_h5'),
                'sub_openid' => $openid,
            ]),
        ];
        $request->setExtendInfo($extendInfoMap);

        // var_dump($extendInfoMap);
        // exit;

        // 发起API调用
        $client = new \BsPaySdk\core\BsPayClient();
        $result = $client->postRequest($request);

        return $this->getResult($result, $trade_no);
    }

    /**
     * 获取支付调用结果
     * @param $result
     * @param $trade_no
     * @return array
     */
    protected function getResult($result, $trade_no)
    {
        if ($result->isError()) {
            //失败处理
            trace('失败处理');
            trace($result->getErrorInfo());
            return ['code' => 0, 'msg' => json_encode($result->getErrorInfo(), JSON_UNESCAPED_UNICODE)];
        } else {
            //成功处理
            $res = $result->getRspDatas();

            trace($res);

            if ($res && !is_string($res) && isset($res['data']) && isset($res['data']['resp_code'])) {

                $resData = $res['data'];
                //resp_code 00000000 00000100 为调用成功
                //trans_stat    交易状态 P: 处理中、S: 成功、F: 失败
                if (($resData['resp_code'] == '00000000' || $resData['resp_code'] == '00000100') && $resData['trans_stat'] != 'F') {
                    $this->transactionModel->where('trade_no', '=', $trade_no)->update(['hf_seq_id' => $resData['hf_seq_id'], 'op_time' => date('Y-m-d H:i:s')]); //请求成功，修改汇付全局流水号。后面查询交易需要此参数
                    return [
                        'code' => 1,
                        'data' => isset($resData['pay_info']) ? json_decode($resData['pay_info']) : $resData['qr_code'], //微信支付:pay_info,支付宝:qr_code
                        'msg' => '支付请求成功',
                        'resp_code' => $resData['resp_code'],
                    ];
                } else {
                    return [
                        'code' => 0,
                        'msg' => $resData['resp_desc'],
                        'resp_code' => $resData['resp_code'],
                    ];
                }
            }
        }

        return [
            'code' => 0,
            'msg' => '支付请求失败',
        ];
    }

}